<?php defined('SYSPATH') or die('No direct script access.');

/**
 * Класс для работы с заками (сохранение, уведомление, получение информации)
 *
 * @author Odarchenko N.D. <odarchenko.n.d@gmail.com>
 */
class Model_Order
{
    /**
     * Ежедневное уведомление о кол-ве новых заказов, если они есть.
     * Обращается в личный кабинет на амазоне за отчетом.
     * Вызывать 1 раз в сутки.
     * Возвращает отправленное сообщение.
     */
    public static function notify($to, $message, $login, $password)
    {
        //Авторизуемся на https://affiliate-program.amazon.com/

        $post = 'query=%2Fgp%2Fassociates%2Fjoin%2Flanding%2Fmain.html&'
                . 'path=%2Fgp%2Fassociates%2Flogin%2Flogin.html&'
                . 'action=sign-in&mode=1&'
                . 'email=' . urlencode($login)
                . '&password=' . urlencode($password);
        
        self::curl(
            'https://affiliate-program.amazon.com/gp/flex/sign-in/select.html',
            $post);
        self::curl(
            'https://affiliate-program.amazon.com/gp/flex/sign-in/select.html',
            $post);

        // Получаем отчет
        $report = self::curl('https://affiliate-program.amazon.com/gp/'
            . 'associates/network/reports/report.html'
            . '?tag=&reportType=earningsReport&program=all'
            . '&periodType=preSelected&preSelectedPeriod=yesterday'
            . '&startMonth=' . date('m') . '&startDay=' . (date('d')-1)
            . '&startYear=' . date('Y') . '&endMonth=' . date('m')
            . '&endDay=' . (date('d')-1) . '&endYear=' . date('Y')
            . '&submit.download_XML.x=61&submit.download_XML.y=13');

        if(!preg_match('#<AMZNShipmentTotals>\s+'
            . '<Earnings>([^<]+)</Earnings>\s+' //1
            . '<Revenue>([^<]+)</Revenue>\s+' //2
            . '<Units>([^<]+)</Units>\s+' //3
            . '</AMZNShipmentTotals>\s+'
            . '<NonAMZNShipmentTotals>\s+'
            . '<Earnings>([^<]+)</Earnings>\s+'//4
            . '<Revenue>([^<]+)</Revenue>\s+' //5
            . '<Units>([^<]+)</Units>\s+' //6
            . '</NonAMZNShipmentTotals>\s+'
            . '<ShipmentTotals>\s+'
            . '<Earnings>([^<]+)</Earnings>\s+'//7
            . '<Revenue>([^<]+)</Revenue>\s+'//8
            . '<Units>([^<]+)</Units>\s+' //9
            . '</ShipmentTotals>\s+'
            . '<ReturnedTotals>\s+'
            . '<Earnings>([^<]+)</Earnings>\s+' //10
            . '<Revenue>([^<]+)</Revenue>\s+' //11
            . '<Units>([^<]+)</Units>\s+' //12
            . '</ReturnedTotals>\s+'
            . '<RefundedTotals>\s+'
            . '<Earnings>([^<]+)</Earnings>\s+' //13
            . '<Revenue>([^<]+)</Revenue>\s+' //14
            . '<Units>([^<]+)</Units>\s+' //15
            . '</RefundedTotals>\s+'
            . '<ReferralFeeTotals>\s+'
            . '<Earnings>([^<]+)</Earnings>\s+' //16
            . '<Revenue>([^<]+)</Revenue>\s+' //17
            . '<Units>([^<]+)</Units>\s+' //18
            . '</ReferralFeeTotals>\s+'
            . '<EventTotals>\s+'
            . '</EventTotals>\s+'
            . '<FinalEarnings>([^<]+)</FinalEarnings>#', $report, $reportArray))
            throw new Exception('XML parsing failed!');

        //print_r($report);

        $message->earnings = $reportArray[19];//FinalEarnings
        $message->earnings1 = $reportArray[1];//AMZNShipmentTotals
        $message->earnings2 = $reportArray[4];//NotAMZNShipmentTotals

        $message->units1 = $reportArray[3];//AMZNShipmentTotals
        $message->units2 = $reportArray[6];//NotAMZNShipmentTotals

        $message->revenue1 = $reportArray[2];
        $message->revenue2 = $reportArray[5];
        $message->revenue3 = $reportArray[11]; // Returned revenue
        $message->revenue4 = $reportArray[14]; // Refunded revenue
        $message->revenue5 = $reportArray[17]; // Referral revenue

        //Если были заказы, отправляем оповещение
        //if($message->earnings > 0)
        {
            $mail = Model::factory('PHPMailer');
            $mail->AddReplyTo($to, 'no reply');
            $mail->From = $to;
            $mail->FromName = 'Shop ' . $_SERVER['HTTP_HOST'];
            $mail->AddAddress($to);
            $mail->Subject  = 'Your store sold some goods yesterday';
            $mail->MsgHTML('<body>' . $message->render() . '</body>');
            $mail->WordWrap = 80;
            if(false == $mail->Send())
                throw new Exception("Email notication: Fail!");
        }
        
        return $message;
    }

    /**
     * Функция для запросов к сторонним сервисам от имени пользователя
     * Нужна для получения отчета из личного кабинета (function notify)
     * @param string $url
     * @param string|array $post
     * @return string
     */
    public static function curl($url, $post = '')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT,
                'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.4');
        curl_setopt($ch, CURLOPT_ENCODING, 'utf-8');
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        if ($post)
        {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }

        if (defined('COOKIES'))
        {
            curl_setopt($ch, CURLOPT_COOKIEFILE, COOKIES);
            curl_setopt($ch, CURLOPT_COOKIEJAR, COOKIES);
        }
        @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    /**
     * Сохранение содержимого корзины в БД
     * @param array $cart
     * @param int $user_id
     */
    public static function save($cart, $user_id)
    {
        if(!count($cart))
            return;
        
        list($insert_id, $total_rows_affected) = DB::insert('orders',
                array('user_id', 'date'))->values(
                        array($user_id, time())
                )->execute();
        
        

        foreach ($cart as $item)
            if(is_array ($item) && isset($item['ASIN'], $item['Quantity'])
                    && $item['Quantity'])
            {
                DB::insert('order_items', array(
                    'asin', 'order_id','title','price','quantity'))
                    ->values(array(
                    $item['ASIN'], $insert_id, $item['Title'],
                        $item['Price'], $item['Quantity'])
                    )->execute();
            }
    }
    
}